﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;

using System.Diagnostics;
using System.Data.Common;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;

namespace SampleAppForAppConfigEncrypt
{
    public partial class frmSettings : Form
    {
        public frmSettings()
        {
            InitializeComponent();
        }
        bool IsNormalKeyTab = true;
        string FilePath;
        Image Logo;
        string Key = ConfigurationManager.AppSettings["MD5"];

        protected override void OnKeyPress(KeyPressEventArgs e)
        {

            base.OnKeyPress(e);
            if (e.KeyChar == '\r' && IsNormalKeyTab)
                SendKeys.Send("{TAB}");
        }

        private void MailSettings_Load(object sender, EventArgs e)
        {
            cmbAuthentication.SelectedItem = "WindowsAuthentication";

            txtUserName.Text = Functions.DecryptMD5(Functions.GetAppSettingByKey("UserName"), Key);
            txtPassword.Text = Functions.DecryptMD5(Functions.GetAppSettingByKey("Password"), Key);
            txtHost.Text = Functions.DecryptMD5(Functions.GetAppSettingByKey("Host"), Key);
            txtPortNumber.Text = Functions.DecryptMD5(Functions.GetAppSettingByKey("Port"), Key);
            txtFromTitle.Text = Functions.DecryptMD5(Functions.GetAppSettingByKey("FromTitle"), Key);
            txtDaysToExpireContract.Text = Functions.DecryptMD5(Functions.GetAppSettingByKey("ContarctExpireDate"), Key);
            txtFilePath.Text = Functions.GetAppSettingByKey("MailTemplatePath");
            GetCofigFromDB();

            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            //   config.ConnectionStrings.ConnectionStrings.Remove("Fire.Properties.Settings.FIREConnectionString");
            string cnString = Functions.DecryptMD5(ConfigurationManager.ConnectionStrings["Fire"].ConnectionString, Key);
            ArrayList dbValue = new ArrayList();
            string[] split = cnString.Split(new Char[] { ';', '=' });
            foreach (string word in split)
            {
                dbValue.Add(word);
            }
            txtServerName.Text = dbValue[1].ToString();
            txtDBName.Text = dbValue[3].ToString();
            if (!(dbValue[5].ToString() == "True"))
            {
                txtDBUserName.Text = dbValue[5].ToString();
                txtDBPassword.Text = dbValue[7].ToString();
                cmbAuthentication.SelectedItem = "SqlAuthentication";
            }
        }
        /// <summary>
        /// Get Confige FormDB In Setting Form
        /// </summary>
        void GetCofigFromDB()
        {
            ConnectionStringSettings settings = null;
            DbProviderFactory factory = null;
            settings = ConfigurationManager.ConnectionStrings["Fire"];
            factory = DbProviderFactories.GetFactory(settings.ProviderName);
            SqlConnection connection = (SqlConnection)factory.CreateConnection();
            try
            {
                connection.ConnectionString = Functions.DecryptMD5(settings.ConnectionString, Key);
                connection.Open();
                DbCommand cmd = connection.CreateCommand();
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "dbo.sp_GetConfig";
                IDataReader dr = cmd.ExecuteReader();
                dr.Read();
                txtCompanyName.Text = dr["CompanyName"].ToString();
                txtManager.Text = dr["Manager"].ToString();
                txtTelephone.Text = dr["Telephone"].ToString();
                txtFax.Text = dr["Fax"].ToString();
                txtSite.Text = dr["Site"].ToString();
                txtEmail.Text = dr["Email"].ToString();
                txtAddress.Text = dr["Address"].ToString();
                txtTaeedKonande.Text = dr["TaeedKonande"].ToString();
                string pic = dr["pic"].ToString();
                if (!(pic == ""))
                {
                    try
                    {
                        if (!(string.IsNullOrEmpty(Functions.GetImage((byte[])dr["pic"]).ToString())))
                            picLogo.Image = Logo = Functions.GetImage((byte[])dr["pic"]);
                        FilePath = Application.StartupPath + "\\temp\\" + picLogo.Name;
                        txtPic.Text = FilePath;
                    }
                    catch
                    {
                        MessageBox.Show("مشکل در خواندن عکس لوگو از دیتابیس", "خطا");
                    }
                }
                dr.Close();
            }
            catch
            {

            }
        }
        /// <summary>
        /// Active Save Button 
        /// </summary>

        private void btnSave_Click(object sender, EventArgs e)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (!ConfigurationManager.AppSettings.AllKeys.Contains("UserName"))
            {
                config.AppSettings.Settings.Add("UserName", Functions.EncryptMD5(txtUserName.Text, Key));
            }
            else
            {
                config.AppSettings.Settings["UserName"].Value = Functions.EncryptMD5(txtUserName.Text, Key);
            }
            if (!ConfigurationManager.AppSettings.AllKeys.Contains("Password"))
            {
                config.AppSettings.Settings.Add("Password", Functions.EncryptMD5(txtPassword.Text, Key));
            }
            else
            {
                config.AppSettings.Settings["Password"].Value = Functions.EncryptMD5(txtPassword.Text, Key);
            }
            if (!ConfigurationManager.AppSettings.AllKeys.Contains("Host"))
            {
                config.AppSettings.Settings.Add("Host", Functions.EncryptMD5(txtHost.Text, Key));
            }
            else
            {
                config.AppSettings.Settings["Host"].Value = Functions.EncryptMD5(txtHost.Text, Key);
            }
            if (!ConfigurationManager.AppSettings.AllKeys.Contains("Port"))
            {
                config.AppSettings.Settings.Add("Port", Functions.EncryptMD5(txtPortNumber.Text, Key));
            }
            else
            {
                config.AppSettings.Settings["Port"].Value = Functions.EncryptMD5(txtPortNumber.Text, Key);
            }
            if (!ConfigurationManager.AppSettings.AllKeys.Contains("FromTitle"))
            {
                config.AppSettings.Settings.Add("FromTitle", Functions.EncryptMD5(txtFromTitle.Text, Key));
            }
            else
            {
                config.AppSettings.Settings["FromTitle"].Value = Functions.EncryptMD5(txtFromTitle.Text, Key);
            }
            if (!ConfigurationManager.AppSettings.AllKeys.Contains("MailTemplatePath"))
            {
                config.AppSettings.Settings.Add("MailTemplatePath", Functions.EncryptMD5(txtFilePath.Text, Key));
            }
            else
            {
                config.AppSettings.Settings["MailTemplatePath"].Value = Functions.EncryptMD5(txtFilePath.Text, Key);
            }
            // Save the configuration file.
            config.Save(ConfigurationSaveMode.Modified);
            // Force a reload of a changed section.
            ConfigurationManager.RefreshSection("appSettings");
            //config.AppSettings.Settings["UserName"].Value = Functions.EncryptMD5(txtUserName.Text, Key);
            //config.AppSettings.Settings["Password"].Value = Functions.EncryptMD5(txtPassword.Text, Key);
            //config.AppSettings.Settings["Host"].Value = Functions.EncryptMD5(txtHost.Text, Key);
            //config.AppSettings.Settings["Port"].Value = Functions.EncryptMD5(txtPortNumber.Text, Key);
            //config.AppSettings.Settings["FromTitle"].Value = Functions.EncryptMD5(txtFromTitle.Text, Key);
            //config.AppSettings.Settings["MailTemplatePath"].Value = txtFromTitle.Text;
            //string path = Application.StartupPath.ToString().Replace("bin\\Debug", "");
            //config.SaveAs(path + "app.config");
            //ConfigurationManager.RefreshSection("appSettings");
            Encryption.EncryptedUserName = txtUserName.Text;
            Encryption.EncryptedPassword = txtPassword.Text;
            Encryption.EncryptedHost = txtHost.Text;
            Encryption.EncryptedPort = txtPortNumber.Text;
            Encryption.EncryptedFromTitle = txtFromTitle.Text;
        }
        /// <summary>
        /// Click On Save Configuration In Setting Form
        /// </summary>

        private void btnSaveConfiguration_Click(object sender, EventArgs e)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
              if (!ConfigurationManager.AppSettings.AllKeys.Contains("ContarctExpireDate"))
            {
                config.AppSettings.Settings.Add("ContarctExpireDate", Functions.EncryptMD5(txtDaysToExpireContract.Text, Key));
            }
            else
            {
                config.AppSettings.Settings["ContarctExpireDate"].Value = Functions.EncryptMD5(txtDaysToExpireContract.Text, Key);
            }
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");

            ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["Fire"];
            DbProviderFactory factory = DbProviderFactories.GetFactory(settings.ProviderName);
            using (DbConnection connection = factory.CreateConnection())
            using (DbCommand cmd = connection.CreateCommand())
            {
                connection.ConnectionString = Functions.DecryptMD5(settings.ConnectionString, Key);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "dbo.Config_Update";
                SqlParameter CompanyName = new SqlParameter("CompanyName", txtCompanyName.Text);
                SqlParameter Manager = new SqlParameter("Manager", txtManager.Text);
                SqlParameter Telephone = new SqlParameter("Telephone", txtTelephone.Text);
                SqlParameter Fax = new SqlParameter("Fax", txtFax.Text);
                SqlParameter Site = new SqlParameter("Site", txtSite.Text);
                SqlParameter Address = new SqlParameter("Address", txtAddress.Text);
                SqlParameter Email = new SqlParameter("Email", txtEmail.Text);
                SqlParameter TaeedKonande = new SqlParameter("TaeedKonande", txtTaeedKonande.Text);
                //SqlParameter Version = new SqlParameter("Version", txtVersion.Text);
                //SqlParameter ReleaseDate = new SqlParameter("ReleaseDate", txtReleaseDate.Text);
                byte[] pic = Functions.GetByteFromFile(openFileDialog1.FileName);
                SqlParameter Pic = new SqlParameter("Pic", pic);
                cmd.Parameters.Add(CompanyName);
                cmd.Parameters.Add(Manager);
                cmd.Parameters.Add(Telephone);
                cmd.Parameters.Add(Fax);
                cmd.Parameters.Add(Site);
                cmd.Parameters.Add(Address);
                cmd.Parameters.Add(Email);
                cmd.Parameters.Add(TaeedKonande);
                //cmd.Parameters.Add(Version);
                //cmd.Parameters.Add(ReleaseDate);
                cmd.Parameters.Add(Pic);
                try
                {
                    connection.Open();
                    cmd.ExecuteNonQuery();
                }
                catch { }
                finally { connection.Close(); }
            }

        }
        /// <summary>
        /// Set Conection String In Setting Form
        /// </summary>

        public void SetConnectionString(string cn)
        {
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.ConnectionStrings.ConnectionStrings[0] = new System.Configuration.ConnectionStringSettings("Fire", cn);
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("connectionStrings");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string conString = "";
            if (cmbAuthentication.SelectedItem.ToString() == "SqlAuthentication")
            {
                conString = "Data Source=" + txtServerName.Text + ";Initial Catalog=" + txtDBName.Text + ";User ID=" + txtDBUserName.Text + ";Password=" + txtDBPassword.Text + ";Connection Timeout=50";
            }
            else
            {
                conString = "Data Source=" + txtServerName.Text + ";Initial Catalog=" + txtDBName.Text + ";Integrated Security=True;Connection Timeout=50";
            }
        
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.ConnectionStrings.ConnectionStrings[0].ConnectionString = String.Format(Functions.EncryptMD5(conString, Key), "testing", "testing2", "Testing6");
            config.ConnectionStrings.ConnectionStrings[1].ConnectionString = String.Format(Functions.EncryptMD5(conString, Key), "testing", "testing2", "Testing6");
             config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("connectionStrings");
            MessageBox.Show("برای اعمال تغییرات برنامه باید مجددا اجرا شود.", "هشدار برای اجرای مجدد برنامه");
            System.Environment.Exit(System.Environment.ExitCode);


        }
        /// <summary>
        /// SelectChange ib Attachment(ComboBox)
        /// </summary>
    
        private void cmbAuthentication_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbAuthentication.SelectedItem.ToString() == "SqlAuthentication")
            {
                txtDBUserName.Enabled = txtDBPassword.Enabled = lblDBPassword.Enabled = lblDBUserName.Enabled = true;
            }
            else { txtDBUserName.Enabled = txtDBPassword.Enabled = lblDBPassword.Enabled = lblDBUserName.Enabled = false; }
        }
        //Active Browse Button 
        private void btnBrowse_Click(object sender, EventArgs e)
        {

            openFileDialog1.Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif";


            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    if ((openFileDialog1.OpenFile()) != null)
                    {
                        txtPic.Text = openFileDialog1.FileName;
                    }
                    picLogo.ImageLocation = openFileDialog1.FileName;
                }
                catch { }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            txtPic.Text = FilePath;
            picLogo.Image = Logo;
        }



    }
}
